package com.koron.order.overhaul.notified;

import com.alibaba.fastjson.JSON;
import com.koron.common.core.util.CodeTools;
import com.koron.order.common.bean.base.OrderType;
import com.koron.order.common.bean.po.OrderExecutePart;
import com.koron.order.common.service.OrderExecutePartService;
import com.koron.order.common.service.OrderExecuteService;
import com.koron.order.overhaul.bean.convertor.OverhaulOrderConvertor;
import com.koron.order.overhaul.bean.entity.OverhaulMajorFormWorker;
import com.koron.order.overhaul.bean.vo.*;
import com.koron.order.overhaul.service.OverhaulMajorFormWorkerService;
import com.koron.order.overhaul.service.OverhaulOrderItemParamsService;
import com.koron.order.overhaul.service.OverhaulOrderMajorFormService;
import com.koron.order.overhaul.service.OverhaulOrderMajorService;
import com.koron.order.overhaul.utils.CommonUtils;
import com.koron.order.overhaul.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author twcao
 * @title: OverhaulOrderExecute
 * @projectName GDH_EAM_V2
 * @description: 大修工单-执行中
 * @date 2021/10/815:04
 */
@Slf4j
@Component
public class OverhaulOrderExecute implements OverhaulOrderNotify<OverhaulOrderMajorVO> {

    @Autowired
    private OverhaulOrderMajorService majorService;

    @Autowired
    private OverhaulOrderMajorFormService formService;

    @Autowired
    private OverhaulOrderItemParamsService paramsService;

    @Autowired
    private OrderExecuteService executeService;

    @Autowired
    private OrderExecutePartService partService;

    @Autowired
    private OverhaulMajorFormWorkerService workerService;

    @Autowired
    private OverhaulOrderConvertor convertor;

    @Override
    public boolean execute(SessionFactory factory, OverhaulOrderMajorVO major) {
        log.info("大修工单-执行中，vo = {}", JSON.toJSONString(major));
        String orderId = major.getOverhaulId();
        // 1、专业基本信息
        if(!StringUtils.isBlank(major.getMajorName())) {
            Assert.hasText(orderId, "工单id不能为空");
            List<OverhaulOrderMajorVO> majorVos = new ArrayList<>();
            majorVos.add(major);
            majorService.saveOrUpdate(factory, convertor.majorVOsToBeans(majorVos));
        }
        // 2、执行信息及零部件
        List<OrderExecuteVO> executes = major.getExecutes();
        if(!CollectionUtils.isEmpty(executes)) {
            Assert.hasText(orderId, "工单id不能为空");
            executes.stream().forEach(execute -> {
                execute.setId(StringUtils.isBlank(execute.getId()) ? CodeTools.getCode32() : execute.getId());
                execute.setCreateTime(new Date());
                execute.setOrderType(OrderType.OVERHAUL);
                // 保存或更新执行信息
                executeService.insertOrUpdate(factory, convertor.executeVoToBean(execute));
                // 删除零部件（防止传入的零部件列表为空时，partService.insertBatch无法正常删除零部件）
                partService.deleteByOrderExecuteId(factory, execute.getId());
                List<OrderExecutePart> parts = execute.getParts();
                if(CollectionUtils.isEmpty(parts)) {
                    return;
                }
                parts.stream().forEach(part -> {
                    part.setId(StringUtils.isBlank(part.getId()) ? CodeTools.getCode32() : part.getId());
                    part.setOrderId(orderId);
                    part.setCreateTime(new Date());
                    part.setOrderType(OrderType.OVERHAUL);
                    part.setExecuteId(execute.getId());
                });
            });
            List<OrderExecutePart> parts = executes.stream().flatMap(row -> row.getParts().stream()).collect(Collectors.toList());
            partService.insertBatch(factory, parts);
        }
        // 3、作业过程项(维护参数)
        List<OverhaulOrderMajorFormVO> forms = major.getForms();
        if(!CollectionUtils.isEmpty(forms)) {
            // 表单
            formService.saveOrUpdate(factory, convertor.formVOsToBeans(forms));
            List<OverhaulOrderItemParamsVO> params = new ArrayList<>();
            List<OverhaulMajorFormWorker> workers = new ArrayList<>();
            forms.stream().forEach(form -> {
                form.setId(StringUtils.isBlank(form.getId()) ? CodeTools.getCode32() : form.getId());
                List<OverhaulMajorFormWorker> formWorkers = form.getFormWorkers();
                if(!CollectionUtils.isEmpty(formWorkers)) {
                    formWorkers.stream().forEach(worker -> {
                        worker.setId(StringUtils.isBlank(worker.getId()) ? CodeTools.getCode32() : worker.getId());
                        worker.setFormId(form.getId());
                        worker.setOverhaulId(orderId);
                        worker.setMajorId(form.getMajorId());
                        workers.add(worker);
                    });
                }
                // 嵌套列表，转成平铺列表
                List<OverhaulOrderItemVO> itemDTOs = (List<OverhaulOrderItemVO>) CommonUtils.tileToList(form.getItemDTOs());
                if(CollectionUtils.isEmpty(itemDTOs)) {
                    return;
                }
                itemDTOs.stream().forEach(item -> {
                    List<OverhaulOrderItemParamsVO> itemParams = item.getItemParams();
                    if(CollectionUtils.isEmpty(itemParams)) {
                        return;
                    }
                    itemParams.stream().forEach(param -> {
                        param.setId(StringUtils.isNotBlank(param.getId()) ? param.getId() : CodeTools.getCode32());
                        param.setOverhaulId(orderId);
                        param.setItemId(item.getId());
                        params.add(param);
                    });
                });
            });
            if(!CollectionUtils.isEmpty(params)) {
                // 删除先前的参数
                paramsService.deleteByOrderIdAndItemId(factory, orderId,params.get(0).getItemId());
                paramsService.saveOrUpdate(factory, convertor.paramVOsToBeans(params));
            }
            if(!CollectionUtils.isEmpty(workers)) {
                workerService.deleteByFormId(factory, workers.get(0).getFormId());
                workerService.saveOrUpdate(factory, workers);
            }
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 9003;
    }

    @Override
    public String getOrderId() {
        return "overhaulId";
    }

    @Override
    public String status() {
        return Constants.OverhaulStatus.EXECUTE;
    }
}
